<template>
  <Page title="搜题结果">
    <template v-slot:navBarCustom>
      <div class="flex items-center navBox">
        <div class="back" @click="back">
          <img class="icon" src="static/icons/back.png" mode="" />
          <span style="color: #fff">搜题结果</span>
        </div>
      </div>
    </template>
    <template v-slot:content>
      <div class="w-full h-full p-20px box-border">
        <div class="container w-full h-full p-20px box-border bg-white flex flex-col">
          <div class="main flex-1 flex flex-col text-333 overflow-scroll">
            <div class="mb-16px text-center" @click="changeImage">
              <img :src="stem" mode="" />
            </div>
            <div class="tips text-FF4040 text-center mb-35px" v-show="!isEditMode">
              未在系统题库中找到题目，请手动选择以下分类添加到错题本（题型和难度非必填）
            </div>
            <div style="height: auto">
              <div class="options flex justify-center">
                <div class="item flex items-center mr-43px">
                  <span class="label inline-block">科目：</span>
                  <el-select
                    v-model="subjects.value"
                    placeholder="请选择"
                    style="width: 2rem"
                    @change="subjects.change($event)"
                  >
                    <el-option
                      v-for="item in subjects.list"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </div>
                <div class="item flex items-center" @click="kPoint.chooseKpointDialogShow()">
                  <span class="label inline-block">知识点：</span>
                  <el-input
                    v-model="kPoint.name"
                    :readonly="true"
                    placeholder="请选择"
                    style="width: 2rem"
                  />
                </div>
              </div>

              <div class="options flex justify-center mt-20px">
                <div class="item flex items-center mr-43px">
                  <span class="label inline-block">题型：</span>
                  <el-select v-model="questionType.value" placeholder="请选择" style="width: 2rem">
                    <el-option
                      v-for="item in questionType.list"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </div>
                <div class="item flex items-center">
                  <span class="label inline-block">难度：</span>
                  <el-select
                    v-model="difficultyLevel.value"
                    placeholder="请选择"
                    style="width: 2rem"
                  >
                    <el-option
                      v-for="item in difficultyLevel.list"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </div>
              </div>
            </div>
          </div>
          <div class="add pt-37px pb-17px">
            <CustomButton class="block" style="width: 4.53rem" @click="submit"
              >{{ isEditMode ? '编辑' : '添加' }}
            </CustomButton>
          </div>
        </div>

        <!-- 选择知识点弹窗 -->
        <div class="dialog-wrap" v-show="kPoint.isShowChooseKpointDialog">
          <div class="choose-kpoint flex flex-col bg-white px-84px py-30px relative">
            <div class="header">
              <img
                class="close absolute"
                src="static/icons/close.png"
                mode=""
                @click="kPoint.isShowChooseKpointDialog = false"
              />
              <div class="w-full title text-center text-262A30 font-medium mb-20px">
                选择知识点
              </div>
            </div>
            <el-input v-model="kPoint.keyword" class="mb-20px" placeholder="搜索知识点" />
            <div class="flex-1 overflow-scroll">
              <el-tree
                :data="kPoint.renderList"
                :props="kPoint.treeProps"
                :highlight-current="true"
                @node-click="kPoint.handleNodeClick($event)"
              ></el-tree>
            </div>
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page/newPage'
import CustomButton from '@/components/button/index'
import {
  createStudentQuestionApi,
  getKpointApi,
  getStudentQuestionTypeApi,
  getStudentQuestionKpointTreeApi,
  updateStudentQuestionApi
} from '@/api/wq-book'
import { mapState, mapActions } from 'vuex'
import { uploadImage } from '@/utils'

export default {
  components: {
    Page,
    CustomButton
  },
  data() {
    return {
      isEditMode: false,
      stem: '',
      explanation: '',
      subjects: {
        vm: this._self,
        value: '',
        list: [],
        change: async function (e, callback = () => {}) {
          if (!e) return

          this.vm.kPoint.value = ''

          // 初始化知识点选项
          this.vm.kPoint.list = []
          this.vm.kPoint.treeList = []
          this.vm.kPoint.renderList = []
          this.vm.kPoint.name = ''
          this.vm.kPoint.value = ''
          this.vm.kPoint.keyword = ''
          const { data } = await getStudentQuestionKpointTreeApi({
            subjectId: e
          })

          if (data.length === 0) return

          const initKPointList = (sourceList, result) => {
            sourceList.forEach((e) => {
              const { childrenList } = e

              if (childrenList.length > 0) {
                const obj = JSON.parse(JSON.stringify(e))
                obj.childrenList = []
                result.push(obj)
                initKPointList(childrenList, result)
              } else {
                result.push(e)
              }
            })

            return result
          }

          this.vm.kPoint.list = initKPointList(data, [])
          this.vm.kPoint.treeList = data
          this.vm.kPoint.renderList = data

          // 初始化题型选项
          const { data: questionTypes } = await getStudentQuestionTypeApi({
            subjectId: e
          })
          this.vm.questionType.list = questionTypes.map((q) => {
            return {
              label: q.typeName,
              value: q.typeId
            }
          })
          callback()
        }
      },
      kPoint: {
        vm: this._self,
        keyword: '',
        isShowChooseKpointDialog: false,
        chooseKpointDialogShow: function () {
          if (!this.vm.subjects.value) {
            this.vm.$message.error('请选择科目')
            return
          }

          if (this.list.length === 0 || this.treeList.length === 0) {
            this.vm.$message.info('知识点加载中...')
            return
          }

          this.isShowChooseKpointDialog = true
          this.vm.$nextTick(() => {
            const treeNodes = document.getElementsByClassName('el-tree-node__expand-icon')

            for (let i = 0; i < treeNodes.length; i++) {
              if (treeNodes[i].className.indexOf('is-leaf') === -1) {
                treeNodes[i].addEventListener('click', () => {}, true)
              }
            }
          })
        },
        treeProps: {
          children: 'childrenList',
          label: 'name'
        },
        name: '',
        value: '',
        list: [],
        treeList: [],
        renderList: [],
        handleNodeClick: function (e) {
          const { id, name } = e

          this.name = name
          this.value = id
          this.isShowChooseKpointDialog = false
        }
      },
      questionType: {
        value: '',
        list: []
      },
      difficultyLevel: {
        value: '',
        list: []
      }
    }
  },
  computed: {
    ...mapState(['wqBook'])
  },
  watch: {
    'kPoint.keyword': function (newVal) {
      if (!newVal) {
        this.kPoint.renderList = this.kPoint.treeList
        return
      }

      const { list } = this.kPoint

      const filters = list.filter((i) => i.name.indexOf(newVal) != -1)
      this.kPoint.renderList = filters
    }
  },
  created() {
    this.init()
  },
  mounted() {
    // console.log(this.$store.state)
  },
  methods: {
    back() {
      if (this.onBack) {
        this.onBack()
      } else {
        this.$router.go(-1)
      }
    },
    ...mapActions(['getDictByType']),
    async init() {
      const {
        questionId = '',
        stem = '',
        explanation = '',
        subject,
        kpointids,
        typeName,
        difficultyLevel
      } = this.wqBook.editingQuestion

      this.stem = stem
      this.explanation = explanation

      // 初始化题目难度选项
      const difficultyLevels = await this.getDictByType('question_difficulty_type')
      this.difficultyLevel.list = difficultyLevels.map((d) => {
        return {
          label: d.label,
          value: d.value
        }
      })

      // 初始化学科选项
      const subjects = await this.getDictByType('subject')
      this.subjects.list = subjects
        .map((s) => {
          if (s.label === '英语听说' || s.value === '66') {
            return null
          }

          return {
            label: s.label,
            value: s.value
          }
        })
        .filter((s) => !!s)

      subject &&
        this.subjects.change(subject, () => {
          if (questionId) {
            this.isEditMode = true

            this.subjects.value = subject + ''
            const kPointId = JSON.parse(kpointids)[0] + ''
            this.kPoint.name = this.kPoint.list.find((i) => i.id === kPointId).name
            this.kPoint.value = kPointId
            if (typeName) {
              this.questionType.value = this.questionType.list.find(
                (t) => t.label === typeName
              ).value
            }
            this.difficultyLevel.value = difficultyLevel
          }
        })
    },
    async changeImage() {
      const { android_call } = window

      if (!android_call) {
        const base64 = await uploadImage()
        this.stem = base64
      } else {
        const callback = (base64) => {
          this.stem = 'data:image/png;base64,' + base64
          this.$message.success('上传成功！')
        }

        const callBackName = `fn${new Date().getTime()}`
        window.android_call[callBackName] = callback.bind(this)

        android.takePhoto(callBackName)
      }
    },
    async submit() {
      if (!this.isEditMode) {
        // 创建

        if (!this.subjects.value) {
          this.$message.error('请选择科目')
          return
        }

        if (!this.kPoint.value) {
          this.$message.error('请选择知识点')
          return
        }

        const { code, msg } = await createStudentQuestionApi({
          subjectId: this.subjects.value,
          typeId: this.questionType.value,
          imgBase64: this.stem.replace('data:image/png;base64,', ''),
          kpointIdList: [this.kPoint.value],
          difficultyLevel: this.difficultyLevel.value
        })

        if (code == 400) {
          this.$message.error(msg)
        } else {
          this.$popup.show({
            type: 'alert',
            success: (popup) => {
              popup.$on('confirm', () => {
                this.$popup.hide('alert')
                this.$router.replace('/pages/wq-book/index/index')
              })
              popup.setData({
                content: '已成功添加1道题到错题本！',
                confirmText:'完成'
              })
            }
          })
        }
      } else {
        // 编辑
        const { questionId = '' } = this.wqBook.editingQuestion

        if (!this.subjects.value) {
          this.$message.error('请选择科目')
          return
        }

        if (!this.kPoint.value) {
          this.$message.error('请选择知识点')
          return
        }

        const { data: success } = await updateStudentQuestionApi({
          id: questionId,
          subjectId: this.subjects.value,
          typeId: this.questionType.value,
          imgBase64: this.stem.replace('data:image/png;base64,', ''),
          kpointIdList: [this.kPoint.value],
          difficultyLevel: this.difficultyLevel.value
        })

        if (success) {
          this.$router.replace('/pages/wq-book/index/index')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.navBox {
  padding: 0 20px;
  box-sizing: border-box;
}
.back {
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 28px;

  .icon {
    width: 17.14px;
    height: 30px;
    margin-right: 11px;
  }
}
.container {
  border-radius: 16px;

  .tips {
    font-size: 18px;
    line-height: 25px;
  }

  .options {
    .item {
      width: 267px;
      height: 44px;
      font-size: 20px;
      line-height: 28px;

      .label {
        width: 90px;
        text-align: end;
      }
    }
  }

  .add {
    margin: 0 auto;
  }
}

.dialog-wrap {
  width: 100vw;
  height: 100vh;
  background: rgba($color: #000000, $alpha: 0.5);
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1999;

  .choose-kpoint {
    width: 567px;
    height: 500px;
    border-radius: 16px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    .close {
      width: 16px;
      height: 16px;
      top: 16px;
      right: 16px;
    }

    .header {
      .title {
        font-size: 22px;
        line-height: 30px;
      }
    }
  }
}

/deep/ .uni-select {
  height: 44px !important;
  font-size: 20px;
  border-radius: 8px;
}

/deep/ .el-tree-node__expand-icon {
  font-size: 18px;
}

/deep/ .el-tree-node__label {
  font-size: 18px;
  line-height: 18px;
}

/deep/ .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background: transparent;

  .el-tree-node__label {
    color: #51c3ff;
  }
}
</style>
